package com.orm.session;

import com.orm.mapping.Configuration;
import com.orm.parser.XmlParser;
import com.orm.pool.Environment;
import com.orm.util.ClassUtil;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.DocumentException;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;


/**
 * 解析xml配置文件，获得连接参数
 *
 * 寻找所有mapper 文件并缓存起来
 *
 * 返回 SqlSessionFactory
 */

@Slf4j
public class SqlSessionFactoryBuilder {
	
	public Configuration getConfigurationFromXml(String configXmlPath) {
		Configuration config = new Configuration();
		XmlParser parser = new XmlParser();
		try{
			InputStream resource = ClassUtil.getResource(configXmlPath);
			parser.load(resource);
			
			Environment environment = parser.parseEnv();
			config.setEnv(environment);
			
			List<String> mapperPaths = parser.parseMapperPaths(config);
			for (String mapperPath : mapperPaths) {
				parser.load(ClassUtil.getResource(mapperPath));
				parser.parseMapper(config);
			}
			
			
			
			// 最后额外解析一次 接口 ?
			parser.parseInterface(config);
			
		} catch (DocumentException e) {
			log.error("解析文档遇到错误");
			e.printStackTrace();
		}finally {
			try {
				parser.close();  //用完就关
			} catch (IOException e) {  //ignore
			}
		}
		return config;
	}
	
	
	public DefaultSqlSessionFactory build(String configXmlPath) {
		Configuration config = getConfigurationFromXml(configXmlPath);
		return new DefaultSqlSessionFactory(config);
	}
}
